package com.hj.system.base.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client extends Thread {
    //定义一个Socket对象
    Socket socket = null;
    MessageInterface messageInterface;

    public Client(String host, int port, MessageInterface messageInterface) {
        try {
            //需要服务器的IP地址和端口号，才能获得正确的Socket对象
            socket = new Socket(host, port);
            this.messageInterface = messageInterface;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage(String message) {
        OutputStream os = null;
        try {
            os = socket.getOutputStream();
            os.write(message.getBytes());
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void run() {
        //客户端一连接就可以写数据个服务器了
        super.run();
        try {
            // 读Sock里面的数据
            InputStream s = socket.getInputStream();
            byte[] buf = new byte[1024];
            int len = 0;
            while ((len = s.read(buf)) != -1) {
                String message = new String(buf, 0, len);
                messageInterface.getMessage(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //函数入口
    public static void main(String[] args) {
        String message = "sdafs";
        //需要服务器的正确的IP地址和端口号
        Client clientTest = new Client("127.0.0.1", 1234, data -> {
            System.out.println("hello " + data);
        });
        clientTest.start();
        clientTest.sendMessage(message);
    }
}
